package jp.gr.java_conf.genzo.wifinotify;

import jp.gr.java_conf.genzo.wifinotify.data.LogTracker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * 設定Activity
 */
public class ExcludeSSIDActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.list_view);

        ListView list = (ListView) findViewById(R.id.excluie_list);
        list.setAdapter(createList());
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
                Bundle b = new Bundle();
                b.putInt(POSITION, position);
                showDialog(DELETE_SSID, b);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            String ssid = intent.getExtras().getString(SSID);
            if (!TextUtils.isEmpty(ssid)) {
                setIntent(null);
                showInputDialog(ssid);
            }
        }
    }

    @Override
    protected void onStop() {
        saveList();
        super.onStop();
        finish();
    }

    private void saveList() {
        ListView list = (ListView) findViewById(R.id.excluie_list);
        ListAdapter adapter = list.getAdapter();

        int count = adapter.getCount();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < count; i++) {
            sb.append(adapter.getItem(i)).append(",");
        }

        if (sb.length() > 0) {
            sb.delete(sb.length() - 1, sb.length());
        }

        AppSettings settings = new AppSettings(this);
        settings.setExcludeSSID(sb.toString());

    }

    private ListAdapter createList() {

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1);

        AppSettings settings = new AppSettings(this);
        String[] ssidList = settings.getExcludeSSID();
        for (String item : ssidList) {
            adapter.add(item);
        }

        if (ssidList.length == 0) {
            Toast.makeText(this,
                    getResources().getString(R.string.msg_no_ssid),
                    Toast.LENGTH_LONG).show();
        }

        return adapter;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.exclude_ssid_menu, menu);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_add:
            showInputDialog();
            return true;
        case R.id.menu_clear:
            showDialog(R.id.menu_clear);
            return true;
        case R.id.menu_add_select:
            showDialog(R.id.menu_add_select);
            return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    private void showInputDialog() {
        showInputDialog("");
    }

    private void showInputDialog(String ssid) {
        Bundle b = new Bundle();
        b.putString(SSID, ssid);
        showDialog(INPUT_DIALOG, b);
    }


    static final private int INPUT_DIALOG = 1;
    static final private int DELETE_SSID = 2;
    static final private String SSID = "ssid";
    static final private String POSITION = "position";

    @Override
    protected Dialog onCreateDialog(final int id, final Bundle args) {
        switch (id) {
        case INPUT_DIALOG:
            final EditText input = new EditText(this);
            input.setText(args.getString(SSID));
            Dialog dialog = new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle(
                    getResources().getString(R.string.input_ssid_title))
                    .setView(input)
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            String ssid = input.getText().toString();
                            if (TextUtils.isEmpty(ssid)) {
                                return;
                            }

                            ListView list = (ListView) findViewById(R.id.excluie_list);
                            ArrayAdapter<String> adapter = (ArrayAdapter<String>) list
                                    .getAdapter();
                            if (adapter.getPosition(ssid) < 0) {
                                adapter.add(ssid);
                            }
                        }
                    }).create();
            dialog.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface arg0) {
                    input.setText("");
                }
            });
            return dialog;
        case DELETE_SSID:
            return new AlertDialog.Builder(ExcludeSSIDActivity.this)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle(
                    getResources()
                    .getString(R.string.delete_ssid_title))
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            ListView list = (ListView) findViewById(R.id.excluie_list);
                            ArrayAdapter<String> adapter = (ArrayAdapter<String>) list
                                    .getAdapter();
                            adapter.remove(adapter.getItem(args
                                    .getInt(POSITION)));

                        }
                    }).setNegativeButton(android.R.string.cancel, null)
                    .create();
        case R.id.menu_clear:
            return new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle(
                    getResources().getString(R.string.clear_ssid_title))
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            ListView list = (ListView) findViewById(R.id.excluie_list);
                            ArrayAdapter<String> adapter = (ArrayAdapter<String>) list
                                    .getAdapter();
                            adapter.clear();

                        }
                    }).setNegativeButton(android.R.string.cancel, null)
                    .create();
        case R.id.menu_add_select:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            final String[] listList = new LogTracker().getSSIDList();
            builder.setTitle(R.string.select_ssid_title);
            builder.setSingleChoiceItems(listList, -1, new DialogInterface.OnClickListener(){
                @Override
                @SuppressWarnings("unchecked")
                public void onClick(DialogInterface arg0, int arg1) {
                    String ssid = listList[arg1];
                    ListView list = (ListView) findViewById(R.id.excluie_list);
                    ArrayAdapter<String> adapter = (ArrayAdapter<String>) list.getAdapter();
                    arg0.dismiss();
                    if (adapter.getPosition(ssid) < 0) {
                        adapter.add(ssid);
                    }
                }
            });

            return builder.create();
        }

        return super.onCreateDialog(id);
    }

}